<template>
    <div class="editImg">
        <div class="filter_box2" v-show="screenSwitch2" v-loading="screenSwitch2" element-loading-text="拼命加载中..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
        </div>
        <div class="filter_box2" v-show="screenSwitch3" v-loading="screenSwitch3" element-loading-text="图片生成中..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
        </div>
        <div class="header">
            <!-- <p class="goback" >
                <img src="../../static/img/left-2.png" alt="">
            </p> -->
            <p class="title">编辑图片</p>
        </div>
        <div class='imgBox'>
            <!-- <div class="backImg" :style="{backgroundImage:'url('+imgList[bgImgIndex]+')',backgroundRepeat:'no-repeat' }" ref="imgBoxBgImg"> -->
            <div class="backImg" :style="{backgroundImage:cartInfo.bgImg,backgroundRepeat:'no-repeat' }" ref="imgBoxBgImg">
                <div class="text">
                    <p class="text_con" ref="textCon">{{cartInfo.text}}</p>
                    <p class="autograph" ref="autograph">{{cartInfo.autograph}}</p>
                </div>
            </div>
            <div class="liBottom">
                <div class="liText">
                    <p class="liTtitle">大家好 我是{{cartInfo.nickname}}</p>
                    <p class="liDes">我将以公益之心服务人民</p>
                    <p class="liDes">以文明作城市之魂奉献社会</p>
                </div>
                <div class="QRcode" ref="qrcode">
                    <img :src="qrcodeImg" alt="">
                </div>
            </div>
        </div>
        <div class="selectImgBox">
            <ul class="selectImgList">
                <li class="addBtn">
                    <label ref="btnOrange" class="btn btn-orange" for="uploads" ><img src="../../static/img/addImg.png"/></label>
                    <input type="file" id="uploads" :value="imgFile" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change.stop="uploadImg($event, 1)">
                </li>
                <li v-for="(item,index) in imgList" :key="index" @click="selectImg(index)" ref="imgItem">
                    <img :src="item" alt="">
                    <transition name="screenSwitch">
                        <div class="selectTrue" v-if="index==imgIndex">
                            <p class="icon"></p>
                        </div>
                    </transition>
                </li>
            </ul>
        </div>
        <div class="line line_box" v-if="lineBoxSwitch">
            <div class="cropper-content" style=" margin-top:-60px;margin-left:260px;">
                <div class="cropper">
                    <VueCropper ref="cropper" :img="option.img" :outputSize="option.size" :outputType="option.outputType" :info="true" :full="option.full" :canMove="option.canMove" :canMoveBox="option.canMoveBox" :original="option.original" :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth"
                        :autoCropHeight="option.autoCropHeight" :fixedBox="option.fixedBox" @realTime="realTime" @imgLoad="imgLoad" @cropMoving="cropMoving"></VueCropper>
                </div>
            </div>
            <div class="btnBottom">
                <input type="button" class="btn btn_cance" value="取消" @click="cancelUploadBtn()">
                <input type="button" class="btn btn_blue" value="确定" @click="finish()">
            </div>
        </div>
        <p class="nextBtn" @click="toEditText()">下一步</p>
    </div>
</template>
<script>
    import { VueCropper} from "vue-cropper";
    export default {
        name: 'editImg',
        components:{VueCropper},
        data() {
            return {
                token: localStorage.getItem("token") ? localStorage.getItem("token") : "",
                tokenParams: {
                    token: localStorage.getItem("token") ?
                        localStorage.getItem("token") : ""
                },
                userInfo:{},
                imgFile:'',
                qrcodeImg:require('../../static/img/qrcode.jpg'),
                imgList:[
                    require('../../static/img/cart1.png'),
                    require('../../static/img/cart2.png'),
                    require('../../static/img/cart3.png'),
                    require('../../static/img/cart4.png'),
                    require('../../static/img/cart6.png'),
                    require('../../static/img/cart7.png'),
                    require('../../static/img/cart8.png'),
                    require('../../static/img/cart10.png'),
                    require('../../static/img/cart11.png'),
                    require('../../static/img/cart12.png'),
                ],
                imgIndex:-1,
                bgImgIndex:0,
                lineBoxSwitch:false,
                screenSwitch2:false,
                screenSwitch3:false,
                /************ */
                bgImg: "",
                //剪切图片上传
                crap: false,
                previews: {},
                option: {
                    img: "",
                    outputSize: 1, //剪切后的图片质量（0.1-1）
                    full: false, //输出原图比例截图 props名full
                    outputType: "png",
                    original: false,
                    canMoveBox: true,
                    canMove: true,
                    canScale: true,
                    autoCrop: true,
                    autoCropWidth: 618,
                    autoCropHeight: 704,
                    fixedBox: true,
                    cropData: {}
                },
                fileName: "", //本机文件地址
                downImg: "#",
                imgFile: "",
                uploadImgRelaPath: "", //上传后的图片的地址（不带服务器域名）,
                cartInfo:{
                    bgImg: '',
                    nickname: '',
                    text: '',
                    autograph: '',
                },
            }
        },
        created(){
            this.getUserInfo();
            this.getCartInfo();
            this.getQrcode();
        },
        beforeRouteLeave(to,from,next){
        //   to.path+='?editFilish=editFilish'
            console.log(to.path)
            next();
        },
        methods: {
            /*判断是否从shareImg中带编辑好之后的图片来二次编辑 */
            // isTowEdit(){
            //     if(this.$route.query.editFilish && localStorage.getItem('cartInfo')){
            //         let cartInfo=JSON.parse(localStorage.getItem('cartInfo'))
            //         this.$nextTick(()=>{
            //             let imgBoxBgImg=this.$refs.imgBoxBgImg;
            //             let textCon=this.$refs.textCon;
            //             let autograph=this.$refs.autograph;
            //             let activeBgImg=cartInfo.bgImg.split('url(\"')[1].split('\")')[0];
            //             imgBoxBgImg.style.backgroundImage=activeBgImg;
            //             textCon.innerText=cartInfo.text;
            //             autograph.innerText=cartInfo.autograph;
            //         })
            //     }
            // },
            getCartInfo(){
                if(localStorage.getItem('cartInfo')){
                    this.cartInfo=JSON.parse(localStorage.getItem('cartInfo'))
                }
            },
            getUserInfo(){
                if(localStorage.getItem('myUserInfo')){
                    this.userInfo=JSON.parse(localStorage.getItem('myUserInfo'))
                }
            },

            // goback(){
            //     if(this.$route.query.editFilish && localStorage.getItem('cartInfo')){
            //         this.$router.push({path:'/wx/shareImg',query:{editFilish:'editFilish'}})
            //     }else{
            //         this.$router.push('/wx/shareImg')
            //     }
            // },
            //选择本地图片
            uploadImg(e, num) {
                var _this = this;
                //上传图片
                var file = e.target.files[0];
                _this.fileName = file.name;
                if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
                    alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
                    return false;
                }
                var reader = new FileReader();
                reader.onload = e => {
                    let data = e.target.result;
                    if (num === 1) {
                        _this.option.img = data;
                    }
                    this.lineBoxSwitch = true;
                };
                // 转化为base64
                reader.readAsDataURL(file);
            },
            realTime(data) {
                this.previews = data;
            },
            imgLoad(msg) {
                console.log(msg);
            },
            cropMoving(data) {
                this.option.cropData = data;
            },
            /*取消上传 */
            cancelUploadBtn() {
                this.lineBoxSwitch = false;
            },
            /*确定上传 */
             //上传图片（点击上传按钮）
            finish() {
                this.screenSwitch3 = true;
                this.lineBoxSwitch = false;
                let _self = this;
                let imgBoxBgImg=this.$refs.imgBoxBgImg;
                let formData = new FormData();
                this.$refs.cropper.getCropBlob(val => {
                    let imgBlob = window.URL.createObjectURL(val);
                    let imgData;
                    let reader = new window.FileReader();
                    reader.readAsDataURL(val);
                    reader.onloadend = function() {
                        imgData = reader.result;
                        formData.append("image", val, _self.fileName);
                        let uploadParams = {
                            file: imgData,
                            token: _self.token
                        };
                        _self.axios
                            .post(_self.APIHOST + "upload/uploadFile", uploadParams)
                            .then(r => {
                                if (r.data.code === "0") {
                                    _self.screenSwitch3 = false;
                                    _self.imgFile = "";
                                    imgBoxBgImg.style.backgroundImage = "url(" + r.data.data.path2 + ")";
                                    _self.$p_message("生成图片成功", "success");
                                } else {}
                                _self.screenSwitch3 = false;
                            }).catch(res=>{
                                        this.$message.error("出错啦,请稍后再试");
                                        setTimeout(() => {
                                        if(_self.screenSwitch3 == true)
                                            _self.screenSwitch3 = false;
                                        }, 1000);
                                    });;
                    }
                });
            },
            /*选择图片 */
            selectImg(index){
                this.$nextTick(()=>{
                    let imgItem=this.$refs.imgItem;
                    this.imgIndex=index;
                    // this.bgImgIndex=index;
                     let imgBoxBgImg=this.$refs.imgBoxBgImg;
                    imgBoxBgImg.style.backgroundImage = `url(${this.imgList[index]})`;
                })
            },
            /*获取二维码图片*/
            getQrcode(){
                this.axios.post(this.APIHOST + "home/appQrcode", this.tokenParams).then(r=>{
                    if(r.data instanceof Array && r.data.length==0){
                        this.qrcodeImg= require('../../static/img/qrcode.jpg')
                    }else{
                            this.qrcodeImg=r.data.data
                    }
                })
            },
            /*去编辑文字页面 */
            toEditText(){
                let cartBgImg=this.$refs.imgBoxBgImg.style.backgroundImage;
                let text=this.$refs.textCon.innerText;
                let autograph=this.$refs.autograph.innerText;
                let nickname=this.userInfo.nickname;
                this.$store.commit('setCartInfo',{bgImg:cartBgImg,text:text,autograph:autograph,nickname:nickname});
                this.$router.push('/wx/editText')
            }
        }
    }
</script>
<style lang="less" scoped>
@import url(../assets/less/public.less);
    .editImg {
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-sizing: border-box;
            padding: 0 4%;
            height: 70px;
            border-bottom: 1px solid #cccccc;
            .goback {
                width: 30px;
                img {
                    width: 100%;
                }
            }
            .title {
                flex-grow: 1;
                text-align: center;
            }
        }
        .imgBox {
            width: 500px;
            margin: 40px auto;
            height: 700px;
            border-radius: 20px;
            overflow: hidden;
            background: @config_bg1;
            position: relative;
            @inputTextarea();
            box-shadow: 0 5px 25px 0 rgba(201, 206, 210, 0.4);
            .backImg {
                height: 547px;
                width: 100%;
                background-size: 100%;
                display: table;
                background-repeat: no-repeat;
                display: flex;
                align-items: center;
                position: relative;
                .text{
                    box-sizing: border-box;
                    padding: 0 4%;
                    color: #ffffff;
                    position: absolute;
                    top: 15vh;
                    .text_con{
                        @font16();
                        text-align: left;
                    }
                    .autograph{
                        text-align: right;
                    }
                    // position: absolute;
                    // top: 30%;
                }
            }
            .liBottom {
                @flex();
                @justify5();
                padding: 20px 40px;
                box-sizing: border-box;
                .liText {
                    text-align: left;
                    .liTtitle {
                        @font16();
                        @color_4();
                        margin-bottom: 10px;
                    }
                    .liDes {
                        @font12();
                        @color_5();
                        line-height: 1.6em;
                    }
                }
                .QRcode {
                    width: 132px;
                    height: 132px;
                    background: @config_bg2;
                    overflow: hidden;
                    img {
                        width: 100%;
                    }
                }
            }
        }
        .selectImgBox{
            width: 92%;
            margin: 0 auto 30px ;
            overflow-x: scroll;
            .selectImgList{
                width: 3000px;
                li{
                    float: left;
                    width: 100px;
                    height: 100px;
                    border-radius: 6px;
                    overflow: hidden;
                    margin-right: 20px;
                    position: relative;
                    img{
                        width: 100px;
                        height: 100px;
                        object-fit: cover;
                    }
                    .selectTrue{
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 100px;
                        height: 100px;
                        border-radius: 6px;
                        background: rgba(0,0,0,0.3);
                        .icon{
                            position: absolute;
                            top: 20px;
                            left: 40px;
                            width:20px;
                            height: 40px;
                            border: 3px solid #4491f5;
                            transform: rotate(45deg);
                            border-top: transparent;
                            border-left:transparent; 
                        }
                    }
                }
                .addBtn{
                    background: #4491f5;
                    position: relative;
                    label{
                        width: 100px;
                        height: 100px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        img{
                            width: 60px;
                            height: 60px;
                        }
                    }
                    input{
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 100px;
                        height: 100px;
                    }
                }

            }
        }
                /*******/
        .line_box {
            position: fixed;
            z-index: 999;
            width: 100%;
            height: 100vh;
            top: 0;
            left: 0;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            .cropper-content {
                width: 618px;
                height: 704px;
                margin: 0 !important;
                .cropper {
                    width: 618px;
                    height: 704px;
                }
            }
            .btnBottom {
                display: flex;
                width: 60%;
                justify-content: center;
                align-items: center;
                .btn_blue {
                    color: #ffffff;
                    background: @config_bg5;
                    border: none;
                    width: 30%;
                    height: 80px;
                    margin-top: 40px;
                    border-radius: 8px;
                    outline: none;
                }
                .btn_cance {
                    margin-right: 30px;
                    color: @config_bg5;
                    background: #ffffff;
                    border: none;
                    width: 30%;
                    height: 80px;
                    margin-top: 40px;
                    border-radius: 8px;
                    outline: none;
                }
            }
        }
        .nextBtn{
            width: 80%;
            height: 60px;
            line-height: 60px;
            text-align: center;
            color: #ffffff;
            background: #4491f5;
            margin: 0 auto;
            border-radius: 60px;
        }
    .screenSwitch-enter-active, .screenSwitch-leave-active {
        opacity: 1;
        transition: opacity 1s;
        }
        .screenSwitch-enter, .screenSwitch-leave-to {
        opacity: 0;
        }
        .filter_box2 {
            width: 100%;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: 100vh;
            @flex();
            @justify2();
            flex-direction: column;
            z-index: 9;
        }
        .screenSwitch2-enter,
        .screenSwitch3-enter {
            opacity: 0;
        }
        .screenSwitch2-enter-active,
        .screenSwitch3-enter-active {
            transition: all 0.1s;
            opacity: 1;
        }
        .screenSwitch2-leave-active,
        .screenSwitch3-leave-active {
            transition: all 0.5s;
            opacity: 0;
        }
    }
</style>

